package com.interviewbackend.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
@Data
public class AliyunOssUploader {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.access-key-id}")
    private String accessKeyId;

    @Value("${aliyun.oss.access-key-secret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucket-name}")
    private String bucketName;

    @Value("${aliyun.oss.dir}")
    private String dir;

    /**
     * 上传文件到阿里云 OSS 并返回公开访问链接
     */
    public String upload(MultipartFile file) throws Exception {
        // 构造唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = dir + UUID.randomUUID() + extension;

        InputStream inputStream = file.getInputStream();

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);
        ossClient.shutdown();

        // 拼接公开访问地址
        return "https://" + bucketName + "." + endpoint + "/" + fileName;
    }
}
